package main

import (
	"database/sql"
	"log"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

func main() {

	// 连接数据库
	db, err := sql.Open("mysql", "root:vader20011014@(localhost:3306)/study?parseTime=true")
	if err != nil {
		log.Fatal(err)
	}

	// 测试连接
	if err = db.Ping(); err != nil {
		log.Fatal(err)
	}
	log.Println("[connected!]")

	// 创建新表
	query := `
		    CREATE TABLE IF NOT EXISTS users(
                id INT AUTO_INCREMENT,
                username TEXT NOT NULL,
                password TEXT NOT NULL,
                created_at DATETIME,
                PRIMARY KEY (id)
            );
	`
	// 执行sql
	if _, err := db.Exec(query); err != nil {
		log.Fatal(err)
	}

	// ----增----
	userName := "alan223"
	password := "psw"
	create_at := time.Now()

	insertQuery := `
		INSERT INTO users (username,password,created_at) VALUES (?,?,?)
	`
	res, err := db.Exec(insertQuery, userName, password, create_at)
	if err != nil {
		log.Fatal(err)
	}

	// 检查
	id, err := res.LastInsertId()
	if err != nil {
		log.Fatal(err)
	}
	log.Println("[inserted]:id#", id)
}
